/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fait.ferm.persists;

import fait.ferm.global.Glob;
import fait.ferm.persists.PersistsObject;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

/**
 *
 * @author Greg
 */
public class Equipment_breakdown extends PersistsObject {
    public Date date_breakdown;
    public int equipment_id;
    public double summa;
    
    public Equipment_breakdown() {
        super();
        table = "equipment_breakdown";
    }
    
    public Equipment_breakdown(int pId) throws Exception {
        super(pId);
        table = "equipment_breakdown";
        load();
    }
    
    @Override
    public void load() throws Exception {
        boolean notSuccessfully=true;
		if(id==-1) {
			throw new Exception("Объект "+table+" отсутствует в базе");
		}	
		try (Statement st = con.createStatement()) {
			String q = "SELECT equipment_id, date_breakdown, summa FROM "+table+" WHERE id = " + id;
			ResultSet rs = st.executeQuery(q);
			if(rs.next()){
				notSuccessfully=false;
                equipment_id = rs.getInt("equipment_id");
                date_breakdown = rs.getDate("date_breakdown");
                summa = rs.getDouble("summa");
			}
			rs.close();
		}
		if(notSuccessfully) {
			throw new Exception("Объект "+table+" не загружен");
        }
    }

    @Override
    protected void update() throws SQLException {
        try (Statement st = con.createStatement()) {
			String q = "UPDATE "+table+" SET date_breakdown="+date_breakdown+
					", summa=" + summa + ", equipment_id=" + equipment_id + " " +
					"WHERE id = " + id;
			st.executeUpdate(q);
		}
    }

    @Override
    protected void createNew() throws SQLException, Exception {
		try (Statement st = con.createStatement()) {
			String q = "INSERT INTO "+table+" "+
					"(date_breakdown, summa, equipment_id) VALUES("+
						date_breakdown + ","+
						summa +
                        equipment_id +
					")";
			st.executeUpdate(q);
			q="SELECT seq FROM sqlite_sequence WHERE name = '"+table+"'";
			ResultSet rs = st.executeQuery(q);
			if(rs.next()){
				id = rs.getInt("seq");
			}
			rs.close();
		}
    }
    
    @Override
	public String toString(){
		return String.valueOf(id);
	}	
    
}
